package per.hnvcam.searchext.text.token.impl;

import java.util.LinkedList;

import per.hnvcam.searchext.text.CommonWords;
import per.hnvcam.searchext.text.WordCounter;
import per.hnvcam.searchext.text.token.TokenHandler;

/**
 * Created by IntelliJ IDEA.
 * User: violon
 * Date: 4/24/11
 * Time: 9:41 PM
 * To change this template use File | Settings | File Templates.
 */
public class DefaultTokenHandlerImpl implements TokenHandler {

   private WordCounter wordCounter;

   private CommonWords commonWords;

   private LinkedList<String> tokenBuffer;

   private StringBuilder wordBuffer;

   private int tokenCountMininum;

   private int tokenCountMaximum;

   public DefaultTokenHandlerImpl() {
      tokenBuffer = new LinkedList<String>();
      wordBuffer = new StringBuilder();
      tokenCountMaximum = 1;
      tokenCountMininum = 1;
   }

   public void handleToken(String token, boolean samePhraseWithPrevious) {
      if (!samePhraseWithPrevious) {
         tokenBuffer.clear();
      }
      String tokenLowerCase = token.toLowerCase();
      if (commonWords.contains(tokenLowerCase)) {
         tokenBuffer.clear();
      }
      else {
         tokenBuffer.addLast(tokenLowerCase);
      }
      if (tokenBuffer.size() > tokenCountMaximum) {
         tokenBuffer.removeFirst();
      }

      wordBuffer.setLength(0);
      int count = 0;

      for (int i = tokenBuffer.size() - 1; i >= 0; i--) {
         if (count > 0) {
            wordBuffer.insert(0, " ");
         }
         wordBuffer.insert(0, tokenBuffer.get(i));
         count++;
         if (count >= tokenCountMininum) {
            wordCounter.count(wordBuffer.toString());
         }
      }
   }

   public int getTokenCountMininum() {
      return tokenCountMininum;
   }

   public void setTokenCountMininum(int tokenCountMininum) {
      this.tokenCountMininum = tokenCountMininum;
   }

   public int getTokenCountMaximum() {
      return tokenCountMaximum;
   }

   public void setTokenCountMaximum(int tokenCountMaximum) {
      this.tokenCountMaximum = tokenCountMaximum;
   }

   public WordCounter getWordCounter() {
      return wordCounter;
   }

   public void setWordCounter(WordCounter wordCounter) {
      this.wordCounter = wordCounter;
   }

   public void setCommonWords(CommonWords commonWords) {
      this.commonWords = commonWords;
   }
}
